﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.IO;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Excel = Microsoft.Office.Interop.Excel;

namespace KnowlegeAssistant
{
    public partial class PrintPreviewForm : Form
    {

        private int archive_test_id;
        private string Html;
        private DataTable testinfo;
        private DataTable questionsinfo;
        private DataTable answersTable;
        private int group_id;
        private DataTable groupData;

        public PrintPreviewForm(int archive_test_id)
        {
            InitializeComponent();
            this.archive_test_id = archive_test_id;
            this.testinfo = DatabaseConnect.execSP("GetTestResults",
                new List<string>() { "0", "0", archive_test_id.ToString() }).Tables[0];
            DataSet tables = TestUtil.GetTestResultsInfo(this.archive_test_id);
            this.questionsinfo = tables.Tables[0];
            this.answersTable = tables.Tables[1];
            GenerateHtmlPreview();
            this.webBrowser1.DocumentText = this.Html;
        }

        public PrintPreviewForm(int archive_test_id, int group_id)
        {
            InitializeComponent();
            List<string> parameters = new List<string>() { };
            parameters.Add("0");
            parameters.Add(group_id.ToString());
            parameters.Add("0");

            this.group_id = group_id;
            this.groupData = DatabaseConnect.execSP("GetTestResults", parameters).Tables[0];

            GenerateHtmlpreviewForGroup();
            this.webBrowser1.DocumentText = this.Html;
        }

        private void GenerateHtmlpreviewForGroup()
        {
            Group g = GroupUtil.GetGroup(this.group_id);

            ;

            string HtmlHeader = "<html><title>" + g.GroupName + " " + g.GroupNumber
                + "</title><body>";

            HtmlHeader += "<p></p>";

            string StatisticsTable = "";

            DataRow[] rows = this.groupData.Select("", "subject_name asc, theme_name asc, fio asc");

            string current_sbj =  rows[0]["subject_name"].ToString();
            string current_theme =  rows[0]["theme_name"].ToString();

            StatisticsTable += "</p><b>Предмет: " + current_sbj + "</b></p>";
            StatisticsTable += "</p><b>Тема: " + current_theme + "</b></p>";

            StatisticsTable += "<p><table cellspacing=\"0\" border=\"1\">";

            StatisticsTable +=
                            "<tr>"
                                + "<td width=\"100\">ФИО</td>"
                                //+ "<td width=\"100\">Предмет</td>"
                                //+ "<td width=\"100\">Тема</td>"
                                + "<td width=\"100\">Верно</td>"
                                + "<td width=\"100\">Неверно</td>"
                                + "<td width=\"100\">Набрано</td>"
                                + "<td width=\"100\">Максимум</td>"
                                + "<td width=\"100\">%</td>"
                                + "<td width=\"100\">Оценка</td>"
                                + "<td width=\"100\">Потрачено</td>"
                                + "<td width=\"100\">Дата</td>"
                            + "</tr>";

            foreach (DataRow row in rows)
            {          

                if (current_sbj != row["subject_name"].ToString() || current_theme != row["theme_name"].ToString())
                {

                    StatisticsTable += "</table></p>";

                    StatisticsTable += "</p><b>Предмет: " + row["subject_name"].ToString() + "</b></p>";
                    StatisticsTable += "</p><b>Тема: " + row["theme_name"].ToString() + "</b></p>";

                    StatisticsTable += "<p><table cellspacing=\"0\" border=\"1\">";

                    StatisticsTable +=
                            "<tr>"
                                + "<td width=\"100\">ФИО</td>"
                               // + "<td width=\"100\">Предмет</td>"
                               // + "<td width=\"100\">Тема</td>"
                                + "<td width=\"100\">Верно</td>"
                                + "<td width=\"100\">Неверно</td>"
                                + "<td width=\"100\">Набрано</td>"
                                + "<td width=\"100\">Максимум</td>"
                                + "<td width=\"100\">%</td>"
                                + "<td width=\"100\">Оценка</td>"
                                + "<td width=\"100\">Потрачено</td>"
                                + "<td width=\"100\">Дата</td>"
                            + "</tr>";
                }

                StatisticsTable +=
                   "<tr>"
                       + "<td width=\"100\">" + row["fio"] + "</td>"
                      // + "<td width=\"100\">" + row["subject_name"] + "</td>"
                      // + "<td width=\"100\">" + row["theme_name"] + "</td>"
                       + "<td width=\"100\">" + row["countoftrue"] + "</td>"
                       + "<td width=\"100\">" + row["countoffalse"] + "</td>"
                       + "<td width=\"100\">" + row["passed_points"] + "</td>"
                       + "<td width=\"100\">" + row["max_points"] + "</td>"
                       + "<td width=\"100\">" + row["percents"] + "</td>"
                       + "<td width=\"100\">" + row["mark"] + "</td>"
                       + "<td width=\"100\">" + row["duration_time"] + "</td>"
                       + "<td width=\"100\">" + row["date_begin"] + "</td>"
                   + "</tr>";

                current_sbj = row["subject_name"].ToString();
                current_theme = row["theme_name"].ToString(); 
            }

            StatisticsTable += "</table></p>";

            string HtmlFooter = "</body></html>";

            Html = HtmlHeader + StatisticsTable + HtmlFooter;
        }

        private void GenerateHtmlPreview()
        {
            string HtmlHeader = "<html><title>" + this.testinfo.Rows[0]["fio"].ToString()
                + ", " + this.testinfo.Rows[0]["subject_name"].ToString()
                + ", " + this.testinfo.Rows[0]["theme_name"].ToString()
                + ", " + this.testinfo.Rows[0]["date_begin"].ToString()
                + "</title><body>";
            string HtmlFooter = "</body></html>";

            string TableForFirstStage = "<table cellspacing=\"0\" border=\"1\">"
                + "<tr><td width=\"100\">№</td>"
                + "<td width=\"100\">Уровень</td>"
                + "<td width=\"60\">Балл</td>"
                + "<td width=\"100\">Верно/Нет</td>"
                + "<td width=\"100\">Начислено</td></tr>";
            string TableForSecondStage = "<table cellspacing=\"0\" border=\"1\">"
                + "<tr><td width=\"100\">№</td>"
                + "<td width=\"100\">Уровень</td>"
                + "<td width=\"60\">Балл</td>"
                + "<td width=\"100\">Верно/Нет</td>"
                + "<td width=\"100\">Начислено</td></tr>";

            string TableForFirstAnswersDetails = "<table cellspacing=\"0\" border=\"1\">";
            TableForFirstAnswersDetails = "<p><b>Первый этап тестирования</b></p>" + TableForFirstAnswersDetails;
            string TableForSecondAnswersDetails = "<table cellspacing=\"0\" border=\"1\">";
            TableForSecondAnswersDetails = "<p><b>Второй этап тестирования</b></p>" + TableForSecondAnswersDetails;

            string HtmlBody = "";

            HtmlBody += "<table>";

            HtmlBody += "<tr><td>Тестируемый:</td><td>" + this.testinfo.Rows[0]["fio"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Группа:</td><td>" + this.testinfo.Rows[0]["group_number"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Предмет:</td><td>" + this.testinfo.Rows[0]["subject_name"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Тема:</td><td>" + this.testinfo.Rows[0]["theme_name"].ToString() + "</td></tr>";
            //HtmlBody += this.testinfo.Rows[0]["countoftrue"] + "</td></tr>";
            //HtmlBody += this.testinfo.Rows[0]["countoffalse"] + "</td></tr>";
            HtmlBody += "<tr><td>Набранный балл:</td><td>" + this.testinfo.Rows[0]["passed_points"].ToString()
                + " из " + this.testinfo.Rows[0]["max_points"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Оценка:</td><td>" + this.testinfo.Rows[0]["mark"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Время прохождения:</td><td>" + this.testinfo.Rows[0]["duration_time"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Дата прохождения:</td><td>" + this.testinfo.Rows[0]["date_begin"].ToString() + "</td></tr>";

            HtmlBody += "</table><p>";

            int i = 1;
            int j = 1;
            string arc_question_id;

            foreach (DataRow row in this.questionsinfo.Rows)
            {
                arc_question_id = row["archive_question_id"].ToString();
                if (row["question_type"].ToString() == "1")
                {
                    TableForFirstStage +=
                        "<tr><td width=\"100\"> Задание " + (i++).ToString() + " </td>"
                        + "<td width=\"100\">" + row["levelname"].ToString() + "</td>"
                        + "<td width=\"100\">" + row["level_value"].ToString() + "</td>"
                        + "<td width=\"100\">" + ((row["true"].ToString() == "0") ? "Да" : "Нет") + "</td>"
                        + "<td>" + ((row["true"].ToString() == "0") ? row["level_value"].ToString() : "0") + "</td></tr>";

                    TableForFirstAnswersDetails += "<tr><td colspan=\"3\"><b>Задание " + (i - 1) + "</b></td></tr>";
                    TableForFirstAnswersDetails += "<tr><td colspan=\"3\">" + row["description"];

                    byte[] img = null;
                    object temp = row["question_image"];
                    if (temp is byte[])
                    {
                        img = (byte[])temp;
                        img = ResizeImg(img);
                        TableForFirstAnswersDetails += String.Format("<p><img src=\"data:image/jpg;base64,{0}\"></p>", Convert.ToBase64String(img));
                    }

                    TableForFirstAnswersDetails += "</td></tr>";

                    //image!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                    foreach (DataRow rowa in answersTable.Select("archive_question_id = " + arc_question_id))
                    {
                        bool checkedsymbol = (((bool)rowa["checked"]) ? true : false);
                        string trueString = "";
                        if ((bool)rowa["true"])
                        {
                            if (checkedsymbol)
                            {
                                trueString = "Верно";
                            }
                            //else
                            //{
                            //    trueString = "Неверно";
                            //}
                        }
                        else if (!(bool)rowa["true"])
                        {
                            if (checkedsymbol)
                            {
                                trueString = "Ошибка";
                            }
                        }

                        string backcolor = "";
                        switch (trueString)
                        {
                            case "": backcolor = "#ffffff"; break;
                            case "Верно": backcolor = "#99ff99"; break;
                            case "Ошибка": backcolor = "#ff7f50"; break;
                        }


                        TableForFirstAnswersDetails += "<tr bgcolor=\"" + backcolor + "\">"
                              + "<td width=\"300\">" + rowa["description"].ToString() + "</td>"
                              + "<td width=\"30\">&nbsp;" + ((checkedsymbol) ? "V" : "-") + "</td>"
                            + "<td width=\"80\">&nbsp;" + trueString + "</td>"
                            + "</tr>";
                    }
                }
                else
                {
                    TableForSecondStage +=
                        "<tr><td>Задание " + (j++).ToString() + "</td>"
                        + "<td>" + row["levelname"].ToString() + "</td>"
                        + "<td>" + row["level_value"].ToString() + "</td>"
                        + "<td>" + ((row["true"].ToString() == "0") ? "Да" : "Нет") + "</td>"
                        + "<td>" + ((row["true"].ToString() == "0") ? row["level_value"].ToString() : "0") + "</td></tr>";

                    TableForSecondAnswersDetails += "<tr><td colspan=\"3\"><b>Задание " + (j - 1) + "</b></td></tr>";
                    TableForSecondAnswersDetails += "<tr><td colspan=\"3\">" + row["description"];

                    byte[] img = null;
                    object temp = row["question_image"];
                    if (temp is byte[])
                    {
                        img = (byte[])temp;
                        img = ResizeImg(img);
                        TableForSecondAnswersDetails += String.Format("<p><img src=\"data:image/jpg;base64,{0}\"></p>", Convert.ToBase64String(img));
                    }

                    TableForSecondAnswersDetails += "</td></tr>";

                    foreach (DataRow rowa in answersTable.Select("archive_question_id = " + arc_question_id))
                    {
                        bool checkedsymbol = (((bool)rowa["checked"]) ? true : false);
                        string trueString = "";
                        string backcolor = "";
                        if ((bool)rowa["true"])
                        {
                            if (checkedsymbol)
                            {
                                trueString = "Верно";
                                backcolor = "#99ff99";
                            }
                            else
                            {
                                trueString = "Ошибка";
                                backcolor = "ffff00";
                            }
                        }
                        else if (!(bool)rowa["true"])
                        {
                            if (checkedsymbol)
                            {
                                trueString = "Ошибка";
                                backcolor = "#ff7f50";
                            }
                        }
                        else { backcolor = "#ffffff"; }

                        //switch (trueString)
                        //{
                        //    case "": backcolor = "#ffffff"; break;
                        //    case "Верно": backcolor = "#99ff99"; break;
                        //    case "Ошибка": backcolor = "#ff7f50"; break;
                        //}

                        TableForSecondAnswersDetails += "<tr bgcolor=\"" + backcolor + "\">"
                            + "<td width=\"300\">" + rowa["description"].ToString() + "</td>"
                            + "<td width=\"30\">&nbsp;" + ((checkedsymbol) ? "V" : "-") + "</td>"
                            + "<td width=\"80\">&nbsp;" + trueString + "</td>"
                            + "</tr>";
                    }
                }
            }

            TableForFirstAnswersDetails += "</table>";
            TableForFirstAnswersDetails = "<p>" + TableForFirstAnswersDetails + "</p>";
            TableForSecondAnswersDetails += "</table>";
            TableForSecondAnswersDetails = "<p>" + TableForSecondAnswersDetails + "</p>";

            TableForFirstStage += "</table>";
            TableForFirstStage = "<p><b>Первый этап тестирования</b></p>" + TableForFirstStage;
            TableForFirstStage = "<p>" + TableForFirstStage + "</p>";
            TableForSecondStage += "</table>";
            TableForSecondStage = "<p><b>Второй этап тестирования</b></p>" + TableForSecondStage;
            TableForSecondStage = "<p>" + TableForSecondStage + "</p>";

            HtmlBody = "<p><b>Общая информация<b></p>" + HtmlBody;
            HtmlBody = "<p>" + HtmlBody + "</p>";

            HtmlBody += TableForFirstStage + TableForSecondStage + TableForFirstAnswersDetails + TableForSecondAnswersDetails;

            this.Html = HtmlHeader + HtmlBody + HtmlFooter;
        }

        private void PrintPreviewForm_Load(object sender, EventArgs e)
        {

        }

        private void InitFields()
        {

        }

        StreamReader streamToPrint = null;
        private void button3_Click(object sender, EventArgs e)
        {
            this.webBrowser1.ShowPrintPreviewDialog();
        }

        private object _missingObj = System.Reflection.Missing.Value;

        private void button1_Click(object sender, EventArgs e)
        {

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "xls-files|*.xls";
            sfd.ShowDialog();

            if (sfd.FileName != "" && sfd.FileName != null)
            {
                Excel.Worksheet oSheet;
                Excel.Application xlApp = new Excel.Application();
                xlApp.Workbooks.Add(Type.Missing);
                xlApp.Interactive = false;
                xlApp.EnableEvents = false;
                oSheet = (Excel.Worksheet)xlApp.ActiveSheet;
                webBrowser1.Document.ExecCommand("SelectAll", false, null);
                webBrowser1.Document.ExecCommand("Copy", false, null);
                oSheet.Paste();
                oSheet.SaveAs(sfd.FileName, Excel.XlFileFormat.xlXMLSpreadsheet,
                    false, false,
                false, false, Excel.XlSaveAsAccessMode.xlNoChange, false, false, false);
                oSheet = null;
                xlApp.Interactive = true;
                xlApp.ScreenUpdating = true;
                xlApp.UserControl = true;

                int id;
                GetWindowThreadProcessId(xlApp.Hwnd, out id);
                Process.GetProcessById(id).Kill();
            }
        }

        [DllImport("user32.dll")]
        static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);

        public byte[] ResizeImg(byte[] b)
        {
            byte[] resbytes = null;

            MemoryStream ms = new MemoryStream(b);
            Bitmap map = new Bitmap(ms);

            int width = map.Width;
            int height = map.Height;

            int nWidth = 200;
            float percent = (nWidth * 100 / (float)width);
            int nHeight = (int)(percent * height) / 100;

            Image result = new Bitmap(nWidth, nHeight);
            using (Graphics g = Graphics.FromImage((Image)result))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(map, 0, 0, nWidth, nHeight);
                g.Dispose();
            }

            MemoryStream msr = new MemoryStream();
            result.Save(msr, System.Drawing.Imaging.ImageFormat.Jpeg);
            resbytes = msr.ToArray();

            msr.Close();
            ms.Close();

            return resbytes;
        }


    }
}
